import {message, Button, Divider, Tabs, DatePicker} from 'antd'
import React, { useState, useRef} from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, Link } from 'umi'
import { queryResignationList, saveResignationInfo, resignApplyBpm, deleteDimissionInfo} from './service'
import CreateForm from './components/CreateForm'
import moment from 'moment';
import {modeList, dimissionTypeList, BPMStatusEnum} from "@/utils/constant";

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

const TableList = (props) => {

  const { personnel = {}, currentUser } = props;
  const {options = {}} = personnel;
  const { jobLevel = [] } = options;
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [tabIndex, setTabIndex] = useState("0");
  const [done, setDone] = useState(false);
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(undefined);
  const { authorities } = currentUser;
  const canDelete = authorities.indexOf("user:info:editall") > -1;

  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width:60,
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
    },
    {
      title: '岗位',
      dataIndex: 'jobname',
      hideInSearch: true,
    },
    {
      title: '职级',
      dataIndex: 'jobLevelId',
      hideInSearch: true,
      render: (text) =>{
        return text!=='-' ? jobLevel.find(item => item.id===text)?.name : '';
      }
    },
    {
      title: '公司名称',
      dataIndex: 'orgname',
      hideInSearch: true,
    },
    {
      title: '部门名称',
      dataIndex: 'unitname',
      hideInSearch: true,
    },
    {
      title: '入职日期',
      dataIndex: 'hiredate',
      render: (text) => {
        return text!=='-' ? moment(text).format('YYYY-MM-DD') : text
      },
      renderFormItem: (item, props) => {
        return <RangePicker {...props} />;
      },
    },
    {
      title: '离职日期',
      dataIndex: 'dimissionTime',
      render: (text) => {
        return text!=='-' ? moment(text).format('YYYY-MM-DD') : text
      },
      hideInSearch: true,
    },
    {
      title: '司龄',
      dataIndex: 'workingYears',
      hideInSearch: true,
    },
    {
      title: '离职方式',
      dataIndex: 'mode',
      hideInSearch: true,
      render: (text, record) => {
        const res = modeList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '离职类型',
      dataIndex: 'dimissionType',
      hideInSearch: true,
      render: (text, record) => {
        const res = dimissionTypeList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
    {
      title: '操作人',
      width:60,
      dataIndex: 'applyName',
      hideInSearch: true,
    },
    {
      title: '操作时间',
      dataIndex: 'applyTime',
      hideInSearch: true,
      render: (text) =>{
        return text!=='-' ? moment(text).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '审批状态',
      dataIndex: 'rurnoverStatus',
      hideInSearch: true,
      valueEnum: BPMStatusEnum
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (item, record) => (
        <>
          {record.rurnoverStatus !== 0 && record.bpmDetailUrl ? <>
            <a onClick={() => window.open(record.bpmDetailUrl)}>审批详情</a>
            {
              canDelete && <>
                <Divider type="vertical"/>
                <a onClick={() => deleteApply(record.id)}>删除</a>
              </>
            }
          </> : ''}
          {record.rurnoverStatus === 0 ?
            <>
              <a onClick={() => Initiate(record)}>发起离职申请</a>
              <Divider type="vertical"/>
              <a onClick={() => edit(record)}>编辑</a>
              <Divider type="vertical"/>
              <a onClick={() => deleteApply(record.id)}>删除</a>
            </> :
            ''}
        </>
      )
    }
  ]

  const handleChangTabIndex = (key) => {
    setTabIndex(key);
    if(key === '0'){
      actionRef.current &&  actionRef.current.reload();
    }else{
      actionRef2.current && actionRef2.current.reload();
    }
  };

  const handleCancel = () => {
    setCurrent(null);
    setVisible(false)
  };

  const addResign = () => {
    setCurrent(null);
    setVisible(true);
  };

  const edit = (record) => {
    setCurrent(record);
    setVisible(true);
  };

  const deleteApply = (id) => {
    deleteDimissionInfo(id).then(res => {
      if (res.flag){
        message.success('离职申请删除成功！');
        actionRef.current.reload();
      }else {
        message.error(res.error)
      }
    })
  };

  const Initiate = (record) => {
    resignApplyBpm(record).then(res => {
      if (res.flag){
        window.open(res.data);
        message.success('发起成功！');
      }else {
        message.error(res.error)
      }
    })
  };

  const handleSubmit = (values) => {
    saveResignationInfo(values).then((res) => {
      setDone(false);
      setCurrent(null);
      setVisible(false);
      if (res.flag) {
        message.success('离职信息保存成功！');
      } else {
        message.error(res.error);
      }
      actionRef.current.reload()
    })
  };

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="0" onChange={handleChangTabIndex}>
        <TabPane tab="待办理" key="0">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            loading={loading}
            request={(params) => queryResignationList(params)}
            columns={columns}
            toolBarRender={(action, { selectedRows }) => [
              <Button type="primary" onClick={() => addResign(null)}>新建</Button>,
              // <Button type="primary" onClick={() => delResign()}>删除</Button>,
            ]}
          />
        </TabPane>
        <TabPane tab="已办理" key="1">
          <ProTable
            actionRef={actionRef2}
            rowKey="id"
            request={(params) => queryResignationList(params,2)}
            columns={columns}
          />
        </TabPane>
      </Tabs>
      <CreateForm
        values={{}}
        done={done}
        current={current}
        visible={visible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
}

export default connect(({ personnel,user }) => ({
  personnel,
  currentUser: user.currentUser,
}))(TableList)
